﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Threading;
using System.Windows.Forms;
using System.Reflection;
using System.Collections;

namespace SyringeControl.Tests
{
    [TestFixture]
    public class Test_MainForm
    {
        EventWaitHandle formLoaded = new AutoResetEvent(false);
        ViewControlModel model;
        MainForm form;

        [SetUp]
        public void SetUp()
        {
            model = new ViewControlModel();
            form = new MainForm(model);
            form.Load += delegate{ formLoaded.Set();};
            ThreadPool.QueueUserWorkItem(delegate
            {
                Application.Run(form);
            });
            if (!formLoaded.WaitOne(1000))
                throw new TimeoutException();
        }

        void Run(Action a)
        {
            form.Invoke(a);
        }


        [Test]
        public void Form_loads()
        {
            Assert.Pass();
        }

        [Test]
        public void Form_is_notified_about_setting_TestedControl()
        {
            Run(() => model.TestedControl = new TextBox{Name = "very strange name"});
            Assert.That(GetChildControlsRecursive(form).Select(c => c.Name).ToList(), Has.Member("very strange name"));
        }

        IEnumerable<Control> GetChildControlsRecursive(Control c)
        {
            foreach (Control child in c.Controls)
            {
                yield return child;
                foreach (var subChild in GetChildControlsRecursive(child))
                    yield return subChild;
            }
        }

        [TearDown]
        public void TearDown()
        {
            Run(form.Close);
        }
    }
}
